#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <strings.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include "Terminal.hpp"

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " port[1024+]\n" << std::endl;
}

struct ThreadData
{
    struct sockaddr_in server;
    int sockfd;
    std::string serverip;
};

void *recv_message(void *args)
{
    ThreadData* td = static_cast<ThreadData*>(args);
    // 接收服务器的响应
    char buffer[1024];
    while(true)
    {
        memset(buffer,0,sizeof(buffer));
        // 接收数据
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);

        ssize_t s = recvfrom(td->sockfd,buffer,1023,0,(struct sockaddr*)&temp,&len);
        if(s > 0)
        {
            buffer[s] = 0;
            // cerr:C++标准库中的一个输出流对象，表示标准错误输出流
            // 输出到标准错误输出流，通过标准错误输出流输出到终端
            std::cerr << buffer << std::endl;
        }
    }
}

// 向服务器发送数据
void *send_message(void* args)
{
    ThreadData* td = static_cast<ThreadData*>(args);
    std::string message;
    socklen_t len = sizeof(td->server);

    std::string welcome = td->serverip;
    welcome += " comming... ";
    sendto(td->sockfd,welcome.c_str(),welcome.size(),0,(struct sockaddr*)&td->server,len);

    while(true)
    {
        std::cout << "Please Enter@ ";
        std::getline(std::cin, message);

        // sendto：向指定目标地址发送数据报
        sendto(td->sockfd,message.c_str(),message.size(),0,(struct sockaddr*)&(td->server),len);
    }
}

int main(int argc,char *argv[])
{
    // 判断指令个数是否正确
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }

    // 接收目标ip和端口号
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    // 进行转换
    struct ThreadData td;
    // 将一段内存区域清零
    bzero(&td.server,sizeof(td.server));
    // 赋值
    td.server.sin_family = AF_INET;
    td.server.sin_port = htons(serverport);
    td.server.sin_addr.s_addr = inet_addr(serverip.c_str());

    // 创建套接字
    td.sockfd = socket(AF_INET,SOCK_DGRAM,0);
    if(td.sockfd < 0)
    {
        std::cout << "socker error" << std::endl;
        return 1;
    }

    td.serverip = serverip;

    pthread_t recvr, sender;
    pthread_create(&recvr,nullptr,recv_message,&td);
    pthread_create(&sender,nullptr,send_message,&td);

    pthread_join(recvr,nullptr);
    pthread_join(sender,nullptr);

    close(td.sockfd);
    return 0;
}